<*****对抗演练*****>
<template>
	<search-table
			:columns="hxRouterVmsCol" 
			:data="hxRouterVmsData"
            :total= hxRouterVmsTotal
            @change-page="changePage"
            @change-size="changeSize"
            :page.sync="pqueryRouteInfo.page"
            :size.sync="queryRouteInfo.pageSize">
			<Alert type="warning" show-icon v-if="type != 5" slot="alert">
				<p style="color:#f90">注意事项:</p>
				<p>	1.“答题环境路由配置”看到的规则都是“题目分配”中下发的规则</p>
				<p>	2.如果状态为失败，可以重新下发</p>
				<p>	3.如果下发内容有误，可以修改下发内容重新下发</p>
			</Alert>
			<template slot="search">

			</template>
	<Modal v-model="addHxRouters" :title="titleMObj.str" :mask-closable = "false" footer-hide :width="700">
		<div v-if="type != 5">
			<label color="blue" style="margin-bottom:20px;display: inline-block;vertical-align: middle;">路由规则: </label>
			<Input v-model.trim="hxRouterformValidate.content" placeholder="路由规则" type="textarea"
			   style="margin-bottom: 20px;"
			   :autosize="{minRows: 2,maxRows: 8}"/>
		</div>
		<div v-if="type == 5" style="margin-bottom:20px;">
			  <label color="blue" style="display: inline-block;vertical-align: middle;">外网IP: </label>
			<!--<Input v-model.trim="IP" style="margin-bottom: 20px;"
			  ></Input>-->
			  <Select filterable  v-model="IP" filterable style="width:200px">
				 <Option v-for="item in availableIPs" :value="item" :key="item" :title="item.name">{{item}}</Option>
			 </Select>
		</div>
		<Transfer v-if="addHxRouters"
				  class="horizontally"
			:list-style="tranStyle"
			:data="hxRouterVmList"
			:target-keys="selHxRouterList"
			filterable
			:filter-method="filterMethod"
			@on-change="getSelHxRouterVms"
			@on-selected-change="handleSelRouter">
		</Transfer>
		<!--<Table border :columns="hxRouterVmsCol" :data="hxRouterVmsData" class="drillsTable" style="margin-top:20px;"></Table>-->
	  </Modal>
	  <Modal
		  v-model="reDisRouterModal"
		  title="重新下发路由"
		  :mask-closable = "false"
		  :width="700"
		  @on-ok="reDisRouter">
		  <label color="blue" style="margin-bottom:20px;display: inline-block;vertical-align: middle;">路由规则: </label>
		  <Input v-model.trim="routerContent" placeholder="路由规则" type="textarea" style="margin-bottom: 20px;"
			:autosize="{minRows: 5,maxRows: 10}"></Input>
	  </Modal>
	  </search-table>
</template>

<script>
//import {getTargetTeamList_new} from '@/api/drill_compete'
  import tableToolTip from '@/view/drill_compete/page/tableTooltip.vue'
  import {getHxRouterVmsStatus,delHxRouterVms,hxRouterVms,hostDetail} from '@/api/drill'
  import {queryVmWithParty,modifyPort,getAvailableIP,getDevicePorts,getSceneProject,queryNetworkList} from '@/api/drill_compete'
  export default {
    name: 'scenes',
	components:{tableToolTip},
	props:['type','projectInfo','disabledAllBtn', 'onlineMode'],
    data(){
      return {
      	IP:'',//外网IP
      	tranStyle:{
      		width:'240px'
      	},
      	addHxRouters:false,
      	titleMObj:{
      		str:'下发路由'
      	},
      	selHxRouterList:[],
      	hxRouterVmList:[],
      	hxRouterVmsData:[],
      	hxRouterformValidate: {
          cpntent: '',
          content:''
        },
//      checkId:'',
		keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
      	hxRouterVmsCol: [
      	  {
            title: '规则名称',
            key: 'name',
            align: 'center',
            ellipsis: true,
            tooltip: true,
            placement:'top-left',
            order:1,
            render:(h,params) => {
            	let str = ((params.row.name ? params.row.name : '') + (params.row.description ? `(${params.row.description})` : '')) || '无'
				return h('Tooltip',{
					'class':'tableTooltip',
					props:{
						maxWidth:400,
						placement:'top',
						triggle:'hover',
						transfer:true
					}
				},[
					h('p',{
						'class':'showContent',
						style:{
							maxWidth:'480px'
						}
					}, str),
					h('div',{
						'class':'tooltipContent',
						slot:'content'
					}, str)
				])
            },
			  width: 240
//          width: 150
          },
      	  {
            title: '网络名称',
            key: 'networkName',
            align: 'center',
            ellipsis: true,
            tooltip: true,
            width: 100
          },
          {
            title: 'IP',
            key: 'ip',
            align: 'center',
            ellipsis: true,
            tooltip: true,
            width: 110
//          width: 150
          },
          {
            title: '下发的状态',
            key: 'statusCHName',
            align: 'center',
            ellipsis: true,
            tooltip: true,
			  width: 86,
            render:(h,params) => {
            	return h('span', {
            		style: {
            			display: 'flex'
					}
				}, [
            		h('span', {
            			style: {
            				color: params.row.statusCHName === '执行成功' ? '#19be6b' : '#ed4014'
						}
					}, params.row.statusCHName),
            		h('Tooltip',{
            			style:{
            				display: params.row.status == 3 ? 'inline-block' : 'none'
            			},
		            	props:{
		            		content:params.row.errorMessage,
		            		'max-width':200,
		            		'transfer':true
		            	}
	            	},[
		            	h('Icon',{
		            		style:{
		            			color:'red',
		            			paddingLeft:'5px'
		            		},
			            	props:{
			            		size:20,
			            		type:"ios-information-circle-outline",

			            	}
		            	})
	            	])
            	])
            }
//          width: 150
          },
          // {
          // 	type:'expand',
          // 	title: '内容',
          // 	key:'content',
          // 	align: 'center',
			//   width: 600,
          // 	render:(h, params) => {
          //     	return h(tableToolTip,{
          //     		props:{
          //     			content:this.decode(params.row.content),
          //     			width:600,
          //     			placement:"top",
          //     			triggle:'hover'
          //     		}
          //     	})
          //   }
          // },
          {
          	title: '创建时间',
          	key:'createTime',
          	align: 'center'
          },
//      {
//          title: '错误信息',
////          key: 'errorMessage',
//          align: 'center',
////          ellipsis: true,
////          tooltip: true,
//          render:(h,params) => {
//          	return h('span',{
//	            	style:{
//	            		color:params.row.status == 3 ? 'red' : ''
//	            	}
//          	},params.row.message ? params.row.message : params.row.errorMessage)
//          }
//        },
          {
            title: '操作',
            key: 'os',
            align: 'center',
            ellipsis: true,
            placement:'top-right',
            action:true,
//          width: 185,
            render: (h, params) => {
              return h('div', [
//				h('Poptip', {
//                props: {
//                  confirm: true,
//                  'ok-text': "确定",
//                  'cancel-text': "取消",
//                  type: 'error',
//                  size: 'small',
//                  title: '你确定要重新下发吗?',
//                  transfer:true
//                },
//                on: {
//                  'on-ok': () => {
//                      this.reDisRouterModal = true;
//                      
//						this.routerContent = this.decode(params.row.content);
//						this.curDevice = params.row;
//                  }
//                }
//              }, [
                  h('Button', {
                    props: {
                      type: 'primary',
                      size: 'small',
//                    disabled:params.row.status != 3
                    },
                    on: {
	                    'click': () => {
	                        this.reDisRouterModal = true;
							this.routerContent = this.decode(params.row.content);
							this.curDevice = params.row;
	                    }
	                },
                    style: {
                      marginRight: '5px'
                    },
                  }, '重新下发'),
//              ]),
                h('Poptip', {
                  props: {
                    confirm: true,
                    'ok-text': "确定",
                    'cancel-text': "取消",
                    type: 'error',
                    size: 'small',
                    title: '你确定要删除吗?',
                    transfer:true
                  },
                  on: {
                    'on-ok': () => {
                      this.deleteHxRouterVm(params)
                    }
                  }
                }, [
                  h('Button', {
                    props: {
                      type: 'error',
                      size: 'small'
                    },
                    style: {
                      marginRight: '5px'
                    },
                  }, '删除')
                ])
              ])
            }

          }
        ],
        hxRouterVmsTotal:0,
        queryRouteInfo:{
        	page: 1,
            pageSize: 10,
            projectId: this.$route.query.prjid
        },
        availableIPs:[],
        publicSubnetId:'',
        subnetList:[],
        idwithName:{},
        reDisRouterModal:false,
        routerContent:''
      }
    },
    watch:{

    },
    filters:{

    },
    computed:{
    },
    mounted(){
      this.getHxRouterVms();
      if(this.type == 5){
      	 this.getSceneProject();
      }
//    this.getProjectSubnet();
    },
    beforeDestroy(){

    },
    methods:{
      //进入下发核心路由器的页面
      hxRouters(obj) {
      	this.IP = '';
        this.addHxRouters = true;
        this.hxRouterformValidate.content = '';
//      this.CheckId = obj.row.checkId;
//      this.selVmList = [];
//      this.vmList = [];
//      this.flagVmsData = [];
//      this.flagType = 1;
        this.getHXAllVmlist();
		// 下发路由成功后清空搜索条件，回退到首页
		this.queryRouteInfo.page = 1
        this.getHxRouterVms();
      },
      //下发核心交换机获取场景下所有虚拟机的
      getHXAllVmlist() {
        let _this = this;
        let params = {}
        params.page = 1;
        params.pageSize = 2147483647;
        params.projectId = this.$route.query.prjid;
        params.findPorts = true;
        params.sortBy = 'name';
		params.order = 'asc';
//      params.vmType = 'DRT';
		if(this.type == 5){
			params.vmType = 'PRT';
		}
        queryVmWithParty(params.projectId,params).then(data => {
          _this.hxRouterVmList = [];
          if (data.code == 1) {
            data.data.list.forEach(item => {
              item.key = item.id;
              item.label = '(' + item.networkName + ')' + item.name;
//            console.info(item.key)
//            console.info(item.label)
            })
            _this.hxRouterVmList = data.data.list;
            this.hxRouterVmList.forEach(vm => {
      			this.$set(vm,'disabled',false);
	      	})
          }
        })
      },
      getSelHxRouterVms(newTargetKeys, direction, moveKeys) {
        let _this = this;
		let projectId = this.$route.query.prjid;
        if (direction == 'right') {
        	if(!this.IP && this.type == 5){
				this.$Message.info('请先选择ip');
				this.hxRouterVmList.forEach(vm => {
		  			this.$set(vm,'disabled',false);
		      	})
				return;
			}
          //保存下发核心路由器
          let executionIns = [];
          let ipArr = this.IP.split('/')[0].split('.');
          ipArr.pop();
          let ipNotLast = ipArr.join('.');
          let hwStr = `#!/bin/vbash
					source /opt/vyatta/etc/functions/script-template
					configure
					#internetip为修改后的ip
					internetip=${this.IP}
					#wancidr为外网ip网段
					wancidr=${ipNotLast}`+
					"\nwaneth=`ip a | grep  $wancidr | awk '{print $7}'`\n"+
					"wanip=`ip a | grep  $wancidr | awk '{print $2}'`\n"+
					`#配置端口ip
					del interface ethernet $waneth address
					set interface ethernet $waneth address $internetip
					commit
					save`;
					if(this.type == 5){
						_this.hxRouterformValidate.content = hwStr;
					}
					if(!_this.hxRouterformValidate.content){
						_this.$Message.warning('规则不能为空');
						return;
					}
          let str = _this.encode(_this.hxRouterformValidate.content);
          executionIns = moveKeys.map(deviceId => {
          	let vm = this.hxRouterVmList.filter(vm => vm.id == deviceId)[0];
          	let ip = "192.168.100.1";
          	if(this.type == 5){
          		ip = '192.168.100.10'+ vm.name.split('-')[1].substr(0,1);
          	}
//        	this.subnetList.filter(subnet => subnet.id = vm.networkId)[0].ip;
          	return {
          		content: str,
                deviceId: deviceId,
                enableDelete: false,
                enableWrite: true,
                ip: ip,
                password: vm.access[0].password,
                path: "/home/vyos/rule.sh",
                port: vm.access[0].port,
                type: vm.access[0].accessType,
                username: vm.access[0].username,
          	}
          })
//        moveKeys.forEach(item => {
//        	`${item.id}@${item.accesses[0].accessType}@${item.accesses[0].password}@${item.accesses[0].port}@${item.accesses[0].username}`;
//          let device =
//          let tempArr = item.split('@');
//          executionIns.push({
//            content: str,
//            deviceId: tempArr[0],
//            enableDelete: false,
//            enableWrite: true,
//            ip: "192.168.100.1",
//            password: tempArr[2],
//            path: "/home/vyos/rule.sh",
//            port: tempArr[4],
//            type: tempArr[1],
//            username: tempArr[5],
//          })
//        })
          this.selHxRouterList = executionIns;
          hxRouterVms(projectId, executionIns).then(data => {
            if (data.code == 1) {
              _this.$Message.info('核心路由器下发成功');
              if(this.type == 5){
              	//修改端口ip
              	this.modifyPort(moveKeys);
              }
            } else {
              _this.$Message.error(data.message);
            }
          })
        } else {
        	let ids = [];
        	moveKeys.forEach(vmId => {
        		ids = ids.concat(this.hxRouterVmsData.filter(vm => vm.deviceId == vmId).map(ins => ins.id))
        	})
          delHxRouterVms(projectId, ids).then(data => {
            if (data.code == 1) {
              _this.$Message.info('删除核心路由器配置成功')
            } else {
              _this.$Message.error(data.message);
            }
          })
        }

        setTimeout(function() {
          _this.getHxRouterVms();
        }, 2500)

      },
      reDisRouter(){
//    	let projectId = this.$route.query.prjid;
//    	let vm = this.hxRouterVmList.filter(vm => vm.id == device.deviceId)[0];
//    	let ip = "192.168.100.1";
//    	if(this.type == 5){
//    		let ip = '192.168.100.10'+ vm.name.split('-')[1].substr(0,1);
//    	}
//        	this.subnetList.filter(subnet => subnet.id = vm.networkId)[0].ip;
		let device = this.curDevice;
      	let executionIns =  [{
      		content: this.encode(this.routerContent),
            deviceId: device.deviceId,
            enableDelete: false,
            enableWrite: true,
            ip: device.ip,
            password: device.password,
            path: "/home/vyos/rule.sh",
            port: device.port,
            type: device.type,
            username: device.username,
            description:device.description
      	}]
      	hxRouterVms(device.projectId, executionIns).then(data => {
            if (data.code == 1) {
              this.$Message.info('核心路由器下发成功');
              this.getHxRouterVms();
              if(this.type == 5){
              	//修改端口ip
              	this.modifyPort(moveKeys);
              }
            } else {
              this.$Message.error(data.message);
            }
        })
      },
      //获取发核心路由器下发列表
      getHxRouterVms() {
        this.hxRouterVmsData = [];
        this.selHxRouterList = [];
        let _this = this;
//      let pages = _this.currentPage || 1;
//      let rows = _this.PZ || 100000;
//      let params = {
//        page: pages,
//        pageSize: rows,
//        projectId: this.$route.query.prjid
//      };
        getHxRouterVmsStatus(this.queryRouteInfo).then(data => {
          if (data.code == 1) {
            _this.hxRouterVmsData = data.data.pageData;
            _this.hxRouterVmsTotal = data.data.totalCount;
            _this.selHxRouterList = _this.hxRouterVmsData.map(ins => ins.deviceId);
            _this.hxRouterVmsData.forEach(vm => {
            	this.hostDetail(vm)
            })
          }
        }).catch(err => {
          _this.$Message.error('获取失败，请稍后重试')
        })
      },
      changePage(page){
      	this.queryRouteInfo.page = page;
      	this.getHxRouterVms()
      },
      changeSize(size){
      	this.queryRouteInfo.pageSize = size;
      	this.getHxRouterVms()
      },
      //删除下发核心路由器
      deleteHxRouterVm(obj) {
        let _this = this;
        let ids = [];
        ids.push(obj.row.id);
        delHxRouterVms(this.$route.query.prjid, ids).then(data => {
          if (data.code == 1) {
            _this.$Message.info('路由规则删除成功')
			  this.queryRouteInfo.page = (this.hxRouterVmsData.length == 1 && this.queryRouteInfo.page > 1) ?
					  this.queryRouteInfo.page - 1 : this.queryRouteInfo.page;
            _this.getHxRouterVms();
          } else {
            _this.$Message.error(data.message);
          }
        }).catch(err => {
          _this.$Message.error('删除失败，请稍后重试')
        })

      },
      handleSelRouter(source,target){
      	if(this.type == 5 && source.length > 0){
      		this.hxRouterVmList.forEach(vm => {
	      		if(source.includes(vm.id)){
	      			this.$set(vm,'disabled',false);
	      		}else{
	      			this.$set(vm,'disabled',true);
	      		}
	      	})
      	}else{
      		this.hxRouterVmList.forEach(vm => {
      			this.$set(vm,'disabled',false);
	      	})
      	}
      },
      async modifyPort(deviceId){
      	let ports = await this.getDevicePorts(deviceId);
      	let projectId = this.$route.query.prjid;
      	let networkId = this.projectInfo.network.id;
      	let data = {
		  "ipAddress": this.IP.split('/')[0],
		  "portId": ports[0].id,
		  "publicSubnetId": this.publicSubnetId
		}
      	modifyPort(projectId,networkId,data).then(data => {
      		if(data.code == 1){
      			//this.$Message.info(data.message)
      		}else{
      			this.$Message.error(data.message)
      		}
      	}).catch(error => {
      		this.$Message.error('服务异常')
      	})
      },
      getDevicePorts(deviceId){
  	    return new Promise((resolve,reject) => {
  	    	let params = {
	      		projectId:this.$route.query.prjid,
	      		deviceId:deviceId[0],
	      		subnetId:this.publicSubnetId
	      	}
    		getDevicePorts(params).then(data => {
  	 	        if(data.code == 1){
  	 	        	resolve(data.data.items);
  	 	        }else{
  	 	        	this.$Message.error(data.message)
  	 	        }
  	 		}).catch(error => {
      			this.$Message.error('服务异常')
      		})
    	})
      },
      getAvailableIP(){
      	 if(!this.publicSubnetId){
      	 	this.$Message.warning('没有公网子网信息');
      	 	return;
      	 }
      	 let subnetId = this.publicSubnetId;
      	 let count = 200;
      	 getAvailableIP(subnetId,count).then(data => {
      		if(data.code == 1){
      			this.availableIPs = data.data.ranges;
      		}else{
      			this.$Message.error(data.message)
      		}
      	}).catch(error => {
      		this.$Message.error('服务异常')
      	})
      },
      //获取场景工程详情
      getSceneProject(){
      	let params = {
      		page:1,
      		pageSize:1,
      		projectname:this.projectInfo.project.name,
      		type:'protect_network_exercise',
      		status:3
      	}
      	getSceneProject(params).then(data => {
      		if (data.code == 1) {
	            if(data.data.items.length > 0){
	            	this.publicSubnetId = data.data.items[0].projectIn && data.data.items[0].projectIn.publicSubnet.id;
	            	this.getAvailableIP();
	            }else{
	            	this.publicSubnetId = '';
	            }
	//          .filter(item=>item.statusCHName==='部署成功');
	        }else{
	          	this.$Message.error(data.message);
	        }
      	})
      },
	  // private method for UTF-8 encoding
      _utf8_encode(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

          var c = string.charCodeAt(n);

          if (c < 128) {
            utftext += String.fromCharCode(c);
          } else if ((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
          } else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
          }

        }

        return utftext;
      },
      // public method for encoding
      encode(input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = this._utf8_encode(input);

        while (i < input.length) {

          chr1 = input.charCodeAt(i++);
          chr2 = input.charCodeAt(i++);
          chr3 = input.charCodeAt(i++);

          enc1 = chr1 >> 2;
          enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
          enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
          enc4 = chr3 & 63;

          if (isNaN(chr2)) {
            enc3 = enc4 = 64;
          } else if (isNaN(chr3)) {
            enc4 = 64;
          }

          output = output + this.keyStr.charAt(enc1) + this.keyStr.charAt(enc2) + this.keyStr.charAt(enc3) + this.keyStr
            .charAt(enc4);

        }

        return output;
      },
      _utf8_decode(e) {
		  var t = "",r,c1,c2,c3;
		  var n = 0;
		  r = c1 = c2 = 0;
		  while (n < e.length) {
		   r = e.charCodeAt(n);
		   if (r < 128) {
		    t += String.fromCharCode(r);
		    n++
		   } else if (r > 191 && r < 224) {
		    c2 = e.charCodeAt(n + 1);
		    t += String.fromCharCode((r & 31) << 6 | c2 & 63);
		    n += 2
		   } else {
		    c2 = e.charCodeAt(n + 1);
		    c3 = e.charCodeAt(n + 2);
		    t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
		    n += 3
		   }
		  }
		  return t
		},
		decode(e) {
		  var t = "";
		  var n, r, i;
		  var s, o, u, a;
		  var f = 0;
		  e=e.replace(/[^A-Za-z0-9+/=]/g,"");
		  while (f < e.length) {
		   s = this.keyStr.indexOf(e.charAt(f++));
		   o = this.keyStr.indexOf(e.charAt(f++));
		   u = this.keyStr.indexOf(e.charAt(f++));
		   a = this.keyStr.indexOf(e.charAt(f++));
		   n = s << 2 | o >> 4;
		   r = (o & 15) << 4 | u >> 2;
		   i = (u & 3) << 6 | a;
		   t = t + String.fromCharCode(n);
		   if (u != 64) {
		    t = t + String.fromCharCode(r)
		   }
		   if (a != 64) {
		    t = t + String.fromCharCode(i)
		   }
		  }
		  t = this._utf8_decode(t);
		  return t
		},
      hostDetail(vm){
      	let params = {
      		vmIds:this.hxRouterVmsData.map(vm => vm.deviceId)
      	};
      	hostDetail(vm.deviceId).then(data => {
			if(data.code == 1){
				this.$set(vm,'networkName',data.data.networkName)
			}
		  })
        },
        filterMethod (data, query) {
			return data.label.indexOf(query.trim()) > -1;
        },
        getProjectSubnet(){
	    	queryNetworkList(this.$route.query.prjid,this.projectInfo.network.id).then(data => {
	    		if(data.code == 1){
	    			let subnetList = [];
	    			let linkList = [];
	    			data.attribute.editorStage.childs.forEach(item => {
	    				subnetList = subnetList.concat(item.childs);
	    				if(item.links){
	    					linkList = linkList.concat(item.links);
	    				}
	    			})
//	    			this.subnetList = subnetList.filter(subnet => subnet.dataType == 'NW');
	    			subnetList.forEach(subnet => {
	    				let ip;
	    				if(this.type == 5){
	    					let links = linkList.filter(link => link.rightNetId == subnet.networkId && link.leftIpParts.length > 0);
	    					if(links.length > 0){
    							ip = links[0].leftIpParts[0].ipAddress;
	    						this.idwithName[subnet.id] = {
									id:subnet.networkId,
									name:subnet.name,
									ip:ip
								}
	    					}
	    				}
					})
	    		}
	    	})
	    },
	},
    destroyed() {

    }
  }
</script>

<style>
 .horizontally {
	 display: flex;
	 justify-content: center;
	 align-items: center;
 }
</style>
